package es.guiguegon.elyeproj.sampleloaderview;

import es.guiguegon.elyeproj.loaderviewlibrary.LoaderImageView;
import es.guiguegon.elyeproj.loaderviewlibrary.LoaderTextView;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.element.PixelMapElement;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;

import java.io.IOException;

public class MainAbility extends Ability implements Component.ClickedListener {

    private static final int WAIT_DURATION = 5000;
    private LoaderImageView iconImg;
    private LoaderTextView name;
    private LoaderTextView title;
    private LoaderTextView phone;
    private LoaderTextView email;
    private Button btnReset;
    private TaskDispatcher taskDispatcher;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        iconImg = (LoaderImageView) findComponentById(ResourceTable.Id_image_icon);
        name = (LoaderTextView) findComponentById(ResourceTable.Id_txt_names);
        title = (LoaderTextView) findComponentById(ResourceTable.Id_txt_title);
        phone = (LoaderTextView) findComponentById(ResourceTable.Id_txt_phone);
        email = (LoaderTextView) findComponentById(ResourceTable.Id_txt_email);
        btnReset = (Button) findComponentById(ResourceTable.Id_btn_reset);
        btnReset.setClickedListener(this::onClick);
        loadData();
    }

    private void loadData() {
        taskDispatcher = getUITaskDispatcher();
        taskDispatcher.delayDispatch(new Runnable() {
            @Override
            public void run() {
                postLoadData();
            }
        }, WAIT_DURATION);
    }

    private void postLoadData() {
        name.setText("Mr. Donald Trump");
        try {
            Resource resource = getResourceManager().getResource(ResourceTable.Media_trump);
            PixelMapElement pixelMapElement = new PixelMapElement(resource);
            iconImg.setImageElement(pixelMapElement);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
        title.setText("President of United State (2017 - now)");
        phone.setText("+001 2345 6789");
        email.setText(ResourceTable.String_email);
    }

    public void resetLoader() {
        name.resetLoader();
        title.resetLoader();
        phone.resetLoader();
        email.resetLoader();
        iconImg.resetLoader();
        loadData();
    }

    @Override
    public void onClick(Component component) {
        resetLoader();
    }
}
